<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kafka WebSocket Visualization (Cumulative with Charts)</title>
  <script src="https://cdn.socket.io/4.6.1/socket.io.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    .container { display: flex; flex-wrap: wrap; gap: 20px; }
    .chart-container { width: 48%; height: 400px; }
  </style>
</head>
<body>
  <h1>Kafka WebSocket Visualization (Cumulative)</h1>

 <div class="container">
      <!-- 图表 2: 累计展示各个学期男女人数总和 -->
    <div class="chart-container" id="semester-total-chart"></div>
 </div>

  <script>
    const socket = io('http://localhost:5000');

    // 全局累计数据
    const cumulativeData = {
        semesterTotal: {}, // { semester: { male: count, female: count } }
    }

    const semesterTotalChart = echarts.init(document.getElementById('semester-total-chart'));

     const semesterTotalChartOption = {
      title: { text: '累计各个学期男女人数总和', left: 'center' },
      tooltip: { trigger: 'axis' },
      legend: { top: 'bottom' },
      xAxis: { type: 'category', data: [] },
      yAxis: { type: 'value' },
      series: [
        { name: '男', type: 'bar', data: [] },
        { name: '女', type: 'bar', data: [] }
      ]
    };
    semesterTotalChart.setOption(semesterTotalChartOption);

    // 累计数据处理函数
    socket.on('kafka-message', (message) => {
      const parsedMessage = JSON.parse(message.data);
      const introduction = parsedMessage.introduction;
      const result = parsedMessage.result;

           if (introduction.includes('统计各个学期男女人数总和')) {
        const entries = result.split(';').map(entry => {
          const match = entry.match(/Semester: (\d+), Gender: (\d+), Count: (\d+)/);
          if (match) {
            const semester = match[1];
            const gender = match[2] === '1' ? 'male' : 'female';
            const count = parseInt(match[3], 10);

            if (!cumulativeData.semesterTotal[semester]) {
              cumulativeData.semesterTotal[semester] = { male: 0, female: 0 };
            }
            cumulativeData.semesterTotal[semester][gender] += count;
          }
        });

        const semesters = Object.keys(cumulativeData.semesterTotal);
        const maleCounts = semesters.map(s => cumulativeData.semesterTotal[s].male);
        const femaleCounts = semesters.map(s => cumulativeData.semesterTotal[s].female);

        semesterTotalChartOption.xAxis.data = semesters;
        semesterTotalChartOption.series[0].data = maleCounts;
        semesterTotalChartOption.series[1].data = femaleCounts;
        semesterTotalChart.setOption(semesterTotalChartOption);
      }

    });
  </script>

</body>
</html>